package pers.cj.pdos.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.controller.base.BaseController;

import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.excel.ExcelInGoodsOrder;
import pers.cj.pdos.excel.ExcelSaleOrder;
import pers.cj.pdos.service.IInGoodsGoodsService;
import pers.cj.pdos.service.IInGoodsOrderService;
import pers.cj.pdos.service.IInGoodsService;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/inGoods")
public class InGoodsOrderController extends BaseController {
    @Autowired
    IInGoodsOrderService inGoodsOrderService;
    @Autowired
    IInGoodsService inGoodsService;

    @RequiresPermissions("inGoodsOrder:query")
    @RequestMapping("/inGoodsOrder")
    public String inGoodsOrder(Model model) {
        model.addAttribute(getBusinessSet());
        return "inGoodsOrder/inGoodsOrder";
    }

    @RequiresPermissions("inGoodsOrder:insert")
    @RequestMapping("/inGoodsOrderNew")
    public String inGoodsOrderNew(){
        return "/inGoodsOrder/inGoodsOrderNew";
    }

    @RequiresPermissions("inGoodsOrder:insert")
    @RequestMapping("/inGoodsOrderEdit")
    public String inGoodsOrderEdit(Model model, String id){
        model.addAttribute("id",id);
        return "/inGoodsOrder/inGoodsOrderEdit";
    }

    @RequiresPermissions("inGoodsOrder:query")
    @RequestMapping("/inGoodsOrderDetail")
    public String saleOrderDetail(Model model,String id){
        model.addAttribute("id",id);
        return "/inGoodsOrder/inGoodsOrderDetail";
    }

    @ResponseBody
    @RequestMapping("/inGoodsOrder/getList")
    public ResponseList getList(int page,
                                int limit,
                                String close,
                                String search,
                                String no,
                                String goodsName,
                                String remark,
                                String provider,
                                String makeTime1,
                                String makeTime2,
                                String userId,
                                String date1,
                                String date2,
                                String makeUserId,
                                String status){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();

        List<InGoodsOrderVo> inGoodsOrderVoList = inGoodsOrderService.listVo(company.getId(),
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genLikeData(provider),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                null,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                Utils.genInteger(status));
        long count = inGoodsOrderService.count(company.getId(),
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genLikeData(provider),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                null,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                Utils.genInteger(status));
        return ResponseList.success(count,inGoodsOrderVoList);
    }

    @ResponseBody
    @RequiresPermissions("inGoodsOrder:insert")
    @RequestMapping("/inGoodsOrder/add")
    public ResponseEntity add(@RequestBody InGoodsOrderVo inGoodsOrderVo){
        Company company = getCompany();
        InGoodsOrder inGoodsOrder = DataUtil.genEntityFromVo(InGoodsOrder.class, inGoodsOrderVo);
        DataUtil.processEntity(company,inGoodsOrder);
        inGoodsOrder.setInStatus(1);//待转进货
        inGoodsOrder.setStatus(1);//未审核状态
        inGoodsOrder.setMakeUserId(getLoginUserId());
        inGoodsOrder.setMakeTime(new Date());
        List<InGoodsOrderGoods> inGoodsOrderGoodsList = inGoodsOrderVo.getInGoodsOrderGoodsList();

        if (Utils.isEmpty(inGoodsOrder.getNo())){
            return ResponseEntity.fail("编号不能为空");
        }

        if (Utils.isEmpty(inGoodsOrderGoodsList)){
            return ResponseEntity.fail("您未选择任何商品");
        }

        if (inGoodsOrder.getDate() == null){
            return ResponseEntity.fail("业务日期不能为空");
        }

        if (inGoodsOrderService.checkNo(inGoodsOrder.getNo(),company.getId())){
            return ResponseEntity.fail("编号已被使用");
        }


        //处理待转进货和已转进货
        BigDecimal zero = new BigDecimal("0");
        for (int i=0; i<inGoodsOrderGoodsList.size(); i++){
            inGoodsOrderGoodsList.get(i).setId(UuidUtils.getUUID());
            inGoodsOrderGoodsList.get(i).setCompanyId(company.getId());
            inGoodsOrderGoodsList.get(i).setInGoodsOrderId(inGoodsOrder.getId());
            inGoodsOrderGoodsList.get(i).setHasInNumber(zero);
            inGoodsOrderGoodsList.get(i).setWaitInNumber(inGoodsOrderGoodsList.get(i).getNumber());
        }

        inGoodsOrderService.insert(inGoodsOrder,inGoodsOrderGoodsList);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("inGoodsOrder:insert")
    @RequestMapping("/inGoodsOrder/update")
    public ResponseEntity update(@RequestBody InGoodsOrderVo inGoodsOrderVo){
        Company company = getCompany();
        InGoodsOrder inGoodsOrder = DataUtil.genEntityFromVo(InGoodsOrder.class, inGoodsOrderVo);
        DataUtil.processEntity(false, company,inGoodsOrder);
        inGoodsOrder.setStatus(1);//未审核状态
        List<InGoodsOrderGoods> inGoodsOrderGoodsList = inGoodsOrderVo.getInGoodsOrderGoodsList();

        if (Utils.isEmpty(inGoodsOrder.getNo())){
            return ResponseEntity.fail("编号不能为空");
        }

        if (Utils.isEmpty(inGoodsOrderGoodsList)){
            return ResponseEntity.fail("您未选择任何商品");
        }

        if (inGoodsOrder.getDate() == null){
            return ResponseEntity.fail("业务日期不能为空");
        }

        InGoodsOrder old = inGoodsOrderService.getById(inGoodsOrder.getId());
        if (!old.getNo().equals(inGoodsOrder.getNo()) && inGoodsOrderService.checkNo(inGoodsOrder.getNo(),company.getId())){
            return ResponseEntity.fail("编号已被使用");
        }


        //处理待转进货和已转进货
        BigDecimal zero = new BigDecimal("0");
        for (int i=0; i<inGoodsOrderGoodsList.size(); i++){
            inGoodsOrderGoodsList.get(i).setId(UuidUtils.getUUID());
            inGoodsOrderGoodsList.get(i).setCompanyId(company.getId());
            inGoodsOrderGoodsList.get(i).setInGoodsOrderId(inGoodsOrder.getId());
            inGoodsOrderGoodsList.get(i).setHasInNumber(zero);
            inGoodsOrderGoodsList.get(i).setWaitInNumber(inGoodsOrderGoodsList.get(i).getNumber());
        }

        inGoodsOrderService.update(inGoodsOrder,inGoodsOrderGoodsList);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("inGoodsOrder:insert")
    @RequestMapping("/inGoodsOrder/updateImage")
    public ResponseEntity updateImage(@RequestBody InGoodsOrder inGoodsOrder){
        try {
            InGoodsOrder temp = new InGoodsOrder();
            temp.setId(inGoodsOrder.getId());
            temp.setImage(inGoodsOrder.getImage());
            inGoodsOrderService.updateById(temp);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("更新图片失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("inGoodsOrder:close")
    @RequestMapping("/inGoodsOrder/close")
    public ResponseEntity close(@RequestBody InGoodsOrder inGoodsOrder){
        try {
            //检查是否已经关闭
            if (inGoodsOrderService.checkClose(inGoodsOrder)){
                return ResponseEntity.fail("该单据已被关闭，不能重复关闭");
            }

            //先检查是否有未关闭的进货单
            if (inGoodsService.checkByInGoodsOrder(inGoodsOrder.getId())){
                return ResponseEntity.fail("该进货订单有转进货单，建议在作废已转的进货单后再作废该进货订单。");
            }

            inGoodsOrderService.close(inGoodsOrder);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("关闭订单失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("inGoodsOrder:verify")
    @RequestMapping("/inGoodsOrder/batchVerify")
    public ResponseEntity batchVerify(@RequestBody List<InGoodsOrder> list){
        if (Utils.isEmpty(list)){
            return ResponseEntity.fail("未选择数据");
        }
        try {

            inGoodsOrderService.batchVerify(getLoginUserId(), list);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("审核失败");
        }
    }



    @ResponseBody
    @RequiresPermissions("inGoodsOrder:verify")
    @RequestMapping("/inGoodsOrder/batchBackVerify")
    public ResponseEntity batchBackVerify(@RequestBody List<InGoodsOrder> list){
        if (Utils.isEmpty(list)){
            return ResponseEntity.fail("未选择数据");
        }
        try {
            inGoodsOrderService.batchBackVerify(list);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("反审核失败");
        }
    }

    @ResponseBody
    @RequestMapping("/inGoodsOrder/getVoById")
    public ResponseData getVoById(String id){
        return ResponseData.success(inGoodsOrderService.getVoById(id));
    }

    @ResponseBody
    @RequiresPermissions("inGoodsOrder:export")
    @RequestMapping("/inGoodsOrder/export")
    public ResponseData export(String close,
                               String search,
                               String no,
                               String goodsName,
                               String remark,
                               String provider,
                               String makeTime1,
                               String makeTime2,
                               String userId,
                               String date1,
                               String date2,
                               String makeUserId,
                               String status){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();


        List<InGoodsOrderVo> inGoodsOrderVoList = inGoodsOrderService.listVo(company.getId(),
                null,
                null,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genLikeData(provider),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                null,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                Utils.genInteger(status));
        String fileName = "进货订单列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelInGoodsOrder.class);
            sheet1.setSheetName("进货订单信息");
            writer.write(genExcelInGoodsOrderList(inGoodsOrderVoList), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("订单列表导出失败");
        }
    }

    private List<ExcelInGoodsOrder> genExcelInGoodsOrderList(List<InGoodsOrderVo> inGoodsOrderVoList) {
        List<ExcelInGoodsOrder> list = new ArrayList<>();
        BusinessSet businessSet = getBusinessSet();
        for (InGoodsOrderVo vo : inGoodsOrderVoList){
            ExcelInGoodsOrder excel = new ExcelInGoodsOrder();
            excel.setDate(DateUtils.getDate(vo.getDate(), DateUtils.YYYY_MM_DD));
            excel.setNo(vo.getNo());

            if (vo.getStatus() == 1) {
                excel.setStatus("未审核");
            } else if (vo.getStatus() == 2) {
                excel.setStatus("审核未转销售");
            } else if (vo.getStatus() == 3) {
                excel.setStatus("转销售");
            } else {
                excel.setStatus("");
            }

            if (vo.getVerifyUser()!=null) {
                excel.setVerifyUser(vo.getVerifyUser().getName());
            } else {
                excel.setVerifyUser("");
            }
            excel.setProviderNo(vo.getProvider().getNo());
            excel.setProvider(vo.getProvider().getName());
            String goods = "";
            BigDecimal number = new BigDecimal("0");
            for (InGoodsOrderGoodsVo orderGoodsVo : vo.getInGoodsOrderGoodsVoList()){
                number = number.add(orderGoodsVo.getNumber());
                goods += orderGoodsVo.getGoodsVo().getName() + "、";
            }

            excel.setGoods(goods);
            excel.setNumber(PdosUtils.getNumber(number,businessSet));
            excel.setNumber(PdosUtils.getPrice(vo.getTotalAmt(),businessSet));
            excel.setUser(vo.getUser().getName());
            excel.setMakeUser(vo.getMakeUser().getName());
            excel.setRemark(vo.getRemark());
            excel.setClose(vo.getClose() ? "是":"否");
            list.add(excel);
        }
        return list;
    }

    @ResponseBody
    @RequestMapping(value = "/inGoodsOrder/uploadImg", method = RequestMethod.POST)
    public ResponseData uploadImg(MultipartFile imageFile) {
        return processUploadImg(imageFile, "inGoodsOrder");
    }
}
